package com.fangmao.jetpack.room;

import android.content.Context;
import android.os.AsyncTask;

import java.util.List;

import androidx.lifecycle.LiveData;

/**
 * @ProjectName: wman
 * @Package: com.fangmao.jetpack.room
 * @ClassName: WordRepo
 * @Description: java类作用描述
 * @Author: wman
 * @CreateDate: 2020/1/7 17:23
 * @UpdateUser: 更新者
 * @UpdateDate: 2020/1/7 17:23
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class WordRepo {
    private WordDao mWordDao;
    private LiveData<List<Word>> mAllWordLive;

    public WordRepo(Context context) {
        mWordDao = WordDatabase.getDatabase(context).getWordDao();
        mAllWordLive = mWordDao.getAllWordLive();
    }

    public LiveData<List<Word>> getAllWordLive() {
        return mAllWordLive;
    }

    public void insertWord(Word... words) {
        new InsertAsyncTask(mWordDao).execute(words);
    }

    public void updateWord(Word... words) {
        new UpdateAsyncTask(mWordDao).execute(words);
    }

    public void deleteWord(Word... words) {
        new DeleteAsyncTask(mWordDao).execute(words);
    }

    public void clearWord() {
        new ClearAsyncTask(mWordDao).execute();
    }

    static class InsertAsyncTask extends AsyncTask<Word, Void, Void> {
        WordDao mWordDao;

        public InsertAsyncTask(WordDao wordDao) {
            mWordDao = wordDao;
        }

        @Override
        protected Void doInBackground(Word... words) {
            mWordDao.insertWord(words);

            return null;
        }
    }

    static class UpdateAsyncTask extends AsyncTask<Word, Void, Void> {
        WordDao mWordDao;

        public UpdateAsyncTask(WordDao wordDao) {
            mWordDao = wordDao;
        }

        @Override
        protected Void doInBackground(Word... words) {
            mWordDao.updateWord(words);

            return null;
        }
    }

    static class DeleteAsyncTask extends AsyncTask<Word, Void, Void> {
        WordDao mWordDao;

        public DeleteAsyncTask(WordDao wordDao) {
            mWordDao = wordDao;
        }

        @Override
        protected Void doInBackground(Word... words) {
            mWordDao.deleteWord(words);

            return null;
        }
    }

    static class ClearAsyncTask extends AsyncTask<Void, Void, Void> {
        WordDao mWordDao;

        public ClearAsyncTask(WordDao wordDao) {
            mWordDao = wordDao;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            mWordDao.deleteAllWord();
            return null;
        }
    }
}
